<template>
  <div class="home">
    <nav-bar :userImg="model.user_img"></nav-bar>
    <van-tabs v-model="active" swipeable sticky>
      <van-tab
        v-for="(item, index) in category"
        :key="index"
        :title="item.title"
      >
        <van-list
          :immediate-check="false"
          v-model="item.loading"
          :finished="item.finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div class="detail">
            <detail
              class="detailitem"
              :detailitem="categoryitem"
              v-for="(categoryitem, categoryindex) in item.list"
              :key="categoryindex"
            />
          </div>
        </van-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import NavBar from "../components/common/NavBar.vue";
import Detail from "./Detail.vue";
export default {
  components: {
    NavBar,
    Detail,
  },
  data() {
    return {
      model: {},
      category: [],
      active: 0,
    };
  },
  methods: {
    async UserinfoData() {
      if (localStorage.getItem("token")) {
        const res = await this.$http.get("/user/" + localStorage.getItem("id"));
        this.model = res.data[0];
      };
    },
    async selectCategory() {
      const res = await this.$http.get("/category");
      console.log(res);
      this.changeCategory(res.data);
    },
    changeCategory(data) {
      const category1 = data.map((item, index) => {
        item.list = [];
        item.page = 0;
        item.pagesize = 10;
        item.loading = false;
        item.finished = false;
        return item;
      });
      this.category = category1;
      this.selectArticle();
    },
    async selectArticle() {
      const categoryitem = this.categoryItem();
      const res = await this.$http.get("/detail/" + categoryitem._id, {
        params: {
          page: categoryitem.page,
          pagesize: categoryitem.pagesize,
        },
      });
      categoryitem.list.push(...res.data);
      categoryitem.loading = false;
      if(res.data.length < categoryitem.pagesize){
        categoryitem.finished = true
      }
    },
    categoryItem() {
      const categoryitem = this.category[this.active];
      return categoryitem;
    },
    onLoad() {
      const categoryitem = this.categoryItem();
      setTimeout(() => {
        categoryitem.page += 1;
        this.selectArticle();
      }, 1000);
    },
  },
  watch: {
    active() {
      this.selectArticle();
    },
  },
  created() {
    this.UserinfoData();
    this.selectCategory();
  },
};
</script>
<style lang="scss">
.home {
  overflow: hidden;
  background-color: #fff;
  .detail {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    .detailitem {
      margin: 1.389vw 0;
      width: 45%;
    }
  }
}
</style>
